package com.ganbo.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @author ganbo
 * @date 2023/1/1 19:09
 */
public class HelloClient {

    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new StringEncoder());
                    }
                });

        final ChannelFuture connect = bootstrap.connect("127.0.0.1", 8888);
        connect.addListener(future -> {
            if (future.isSuccess()) {
                System.out.println("连接成功。。。");
                final Channel channel = connect.channel();
                channel.writeAndFlush("hello world").addListener(future1 -> {
                    if (future1.isSuccess()) {
                        System.out.println("发送成功");
                    }
                });
            }
        });
    }
}
